package com.gzx.plugin.tjzy.modular.sms.api.strategy.dy.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.gzx.plugin.tjzy.modular.founds.service.GzxFoundsFlowService;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.SMSStrategy;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.common.dto.CommonSmsSendReqDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.common.dto.CommonSmsSendRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.dy.dto.SMSDYReceiptRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.dy.dto.SMSDYReplyRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.dy.dto.SMSDYSendRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.template.SmsTemplateMethod;
import com.gzx.plugin.tjzy.modular.sms.batch.consts.SMSMDConstant;
import com.gzx.plugin.tjzy.modular.sms.batch.enums.GzxSmsSendStatusEnum;
import com.gzx.plugin.tjzy.modular.sms.batch.service.GzxSmsDbService;
import com.gzx.plugin.tjzy.modular.sms.receipt.consts.GzxSendStatusMappingConstant;
import com.gzx.plugin.tjzy.modular.sms.receipt.entity.GzxSmsReceipt;
import com.gzx.plugin.tjzy.modular.sms.receipt.service.GzxSmsReceiptService;
import com.gzx.plugin.tjzy.modular.sms.record.service.GzxSmsRecordService;
import com.gzx.plugin.tjzy.modular.sms.reply.entity.GzxSmsReply;
import com.gzx.plugin.tjzy.modular.sms.reply.service.GzxSmsReplyService;
import com.gzx.plugin.tjzy.modular.supplier.consts.GzxSupplierConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonHttpUtil;

import java.util.*;

/**
 * @author zjt
 * @description
 * @date 2025/7/21 15:28
 */
@Slf4j
@Service
public class SMSDYStrategyImpl extends SmsTemplateMethod implements SMSStrategy {

    @Value("${sms.md.url}")
    private String url;

    @Value("${sms.md.app-id}")
    private String appId;

    @Value("${sms.md.signature}")
    private String signature;

    public SMSDYStrategyImpl(GzxSmsDbService smsDbService, GzxSmsRecordService smsRecordService, GzxSmsReceiptService smsReceiptService, GzxFoundsFlowService foundsFlowService, GzxSmsReplyService smsReplyService) {
        super(smsDbService, smsRecordService, smsReceiptService, foundsFlowService, smsReplyService);
    }

    /**
     * 获取当前供应商
     *
     * @return
     */
    @Override
    public String getCurrentSupplierCode() {
        return GzxSupplierConstant.DY;
    }

    /**
     * 获取短信签名
     *
     * @param city
     * @return
     */
    @Override
    protected String getSignName(String city) {
        if ("天津".equals(city)) {
            return "【天津自贸试验区普惠金融调解中心】";
        }
        if ("盐城".equals(city)) {
            return "【盐城市盐南高新区金和金融调解中心】";
        }
        return "";
    }

    /**
     * 开始发送短信
     *
     * @param commonSmsSendReqDtoList 发送短信的集合
     * @return
     */
    @Override
    protected List<CommonSmsSendRespDto> startSend(List<CommonSmsSendReqDto> commonSmsSendReqDtoList) {
        Map<String, String> phoneMap = new HashMap<>();
        List<JSONObject> smsParam = new ArrayList<>();
        for (CommonSmsSendReqDto commonSmsSendReqDto : commonSmsSendReqDtoList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phone", commonSmsSendReqDto.getPhone());
            jsonObject.put("content", modifySmsSignature(commonSmsSendReqDto.getSignCity(), commonSmsSendReqDto.getMessage()));
            smsParam.add(jsonObject);
            phoneMap.put(commonSmsSendReqDto.getPhone(), commonSmsSendReqDto.getSupplierOrder());
        }
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("appId", appId);
        bodyMap.put("signature", signature);
        bodyMap.put("messageList", smsParam);
        try {
            String respBody = CommonHttpUtil.post(url + SMSMDConstant.ONE_MANY, null, JSON.toJSONString(bodyMap), "岛屿短信发送");
            SMSDYSendRespDto smsDYSendRespDto = JSONObject.parseObject(respBody, SMSDYSendRespDto.class);
            if (smsDYSendRespDto != null && smsDYSendRespDto.getCode() == 0 && CollectionUtil.isNotEmpty(smsDYSendRespDto.getData())) {
                List<CommonSmsSendRespDto> commonSmsSendRespDtoList = new ArrayList<>();
                for (SMSDYSendRespDto.PhoneResult phoneResult : smsDYSendRespDto.getData()) {
                    String supplierOrder = phoneMap.get(phoneResult.getPhone());
                    Integer result = (supplierOrder.endsWith(GzxSupplierConstant.DY) && phoneResult.getCode() != 0) ? GzxSmsSendStatusEnum.FINAL_FAIL.getCode() : phoneResult.getCode();
                    commonSmsSendRespDtoList.add(new CommonSmsSendRespDto(phoneResult.getPhone(), phoneResult.getBizId(), result));
                }
                return commonSmsSendRespDtoList;
            }
            return defaultResp(commonSmsSendReqDtoList, GzxSmsSendStatusEnum.FAIL.getCode(), GzxSupplierConstant.DY);
        } catch (Exception e) {
            log.error("调用岛屿短信接口出现异常", e);
            return defaultResp(commonSmsSendReqDtoList, GzxSmsSendStatusEnum.FAIL.getCode(), GzxSupplierConstant.DY);
        }
    }

    /**
     * 同步短信回执
     *
     * @return
     */
    @Override
    protected List<GzxSmsReceipt> startSyncReceipt() {
        try {
            String respBody = CommonHttpUtil.get(url + SMSMDConstant.RECEIPT + "?appId=" + appId + "&signature=" + signature, "岛屿短信状态查询");
            SMSDYReceiptRespDto smsdyReceiptRespDto = JSONObject.parseObject(respBody, SMSDYReceiptRespDto.class);
            List<GzxSmsReceipt> smsReceiptList = new ArrayList<>();
            if (smsdyReceiptRespDto != null && smsdyReceiptRespDto.getCode() == 0 && CollectionUtil.isNotEmpty(smsdyReceiptRespDto.getData())) {
                String currentDate = CommonDateUtil.getCurrentTimeStr();
                for (SMSDYReceiptRespDto.DYReceiptDetail dyReceiptDetail : smsdyReceiptRespDto.getData()) {
                    GzxSmsReceipt smsReceipt = new GzxSmsReceipt();
                    smsReceipt.setSupplierCode(GzxSupplierConstant.DY);
                    smsReceipt.setFlagType(1);
                    smsReceipt.setPhone(dyReceiptDetail.getPhone());
                    smsReceipt.setMsgId(dyReceiptDetail.getBizId());
                    smsReceipt.setSendTime(dyReceiptDetail.getDeliverTime());
                    smsReceipt.setResultCode(dyReceiptDetail.getStatus());
                    smsReceipt.setMappingStatus(GzxSupplierConstant.MD_SUCCESS.equals(dyReceiptDetail.getStatus()) ? GzxSendStatusMappingConstant.SUCCESS : GzxSendStatusMappingConstant.FAIL);
                    smsReceipt.setAllDetail(JSON.toJSONString(dyReceiptDetail));
                    smsReceipt.setCreateTime(currentDate);
                    smsReceiptList.add(smsReceipt);
                }
            }
            return smsReceiptList;
        } catch (Exception e) {
            log.error("调用岛屿查询接口出现异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 开始同步短信回复
     *
     * @return
     */
    @Override
    protected List<GzxSmsReply> startSyncReply() {
        String respBody = CommonHttpUtil.get(url + SMSMDConstant.REPLY + "?appId=" + appId + "&signature=" + signature, "岛屿短信回复查询");
        SMSDYReplyRespDto smsdyReplyRespDto = JSONObject.parseObject(respBody, SMSDYReplyRespDto.class);
        List<GzxSmsReply> smsReplyList = new ArrayList<>();
        if (smsdyReplyRespDto != null && smsdyReplyRespDto.getCode() == 0 && CollectionUtil.isNotEmpty(smsdyReplyRespDto.getData())) {
            for (SMSDYReplyRespDto.DYReplyDetail dyReplyDetail : smsdyReplyRespDto.getData()) {
                dyReplyDetail.setContent(StringUtils.deleteWhitespace(dyReplyDetail.getContent()).replaceAll("[\\x00-\\x1F]", ""));
                GzxSmsReply smsReply = new GzxSmsReply();
                smsReply.setSupplierCode(GzxSupplierConstant.DY);
                smsReply.setMsgId(dyReplyDetail.getBizId());
                smsReply.setPhone(dyReplyDetail.getPhone());
                smsReply.setReplyContent(dyReplyDetail.getContent());
                smsReply.setReplyTime(dyReplyDetail.getSendTime());
                smsReply.setReplyDetail(JSON.toJSONString(dyReplyDetail));
                smsReplyList.add(smsReply);
            }
        }
        return smsReplyList;
    }

    @Override
    protected boolean isSuccess(String resultCode) {
        return GzxSupplierConstant.DY_SUCCESS.equals(resultCode);
    }

    /**
     * 是否需要根据短信ID分组
     *
     * @return
     */
    @Override
    protected boolean isMsgIdGroup() {
        return false;
    }
}
